package org.example.admin.common.biz.user;

import cn.hutool.core.collection.ListUtil;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.admin.common.convention.exception.ClientException;
import org.example.admin.common.convention.result.Results;
import org.example.admin.config.UserFlowRiskControlConfiguration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.http.MediaType;
import org.springframework.scripting.support.ResourceScriptSource;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Optional;

/**
 * 用户请求访问流量控制过滤器
 *
 * @author weibin
 * @since 2025/10/21 20:59
 */
@Slf4j
@RequiredArgsConstructor
public class UserFlowRiskControlFilter implements Filter {

    private final StringRedisTemplate stringRedisTemplate;
    private final UserFlowRiskControlConfiguration userFlowRiskControlConfiguration;
    private static final String USER_FLOW_RISK_CONTROL_LUA_SCRIPT_PATH = "lua/user_flow_risk_control.lua";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        /*
        实现思路
        利用redis的increment命令
        相同用户在某个时间窗口期间访问的请求数量达到一定限制，那么就告诉他系统繁忙，请稍后重试
        所以需要给每个用户设置一个redis k-v，这个v是一个数字，一定时间内来一次请求就加1
        思考这个过程：我们操作v加1，然后这个k需要有过期时间，不是原子的，所以得使用lua脚本来保证原子性
         */
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource(USER_FLOW_RISK_CONTROL_LUA_SCRIPT_PATH)));
        redisScript.setResultType(Long.class);

        String username = Optional.ofNullable(UserContext.getUsername()).orElse("other");

        // 执行lua脚本
        Long result = null;
        try {
            result = stringRedisTemplate.execute(redisScript, ListUtil.of(username), userFlowRiskControlConfiguration.getTimeWindow());
        } catch (Throwable ex) {
            log.error("执行用户请求流量限制脚本出错", ex);
            handleException(servletResponse, JSON.toJSONString(Results.failure(new ClientException("当前系统繁忙，请稍后再试"))));
            return;
        }

        if (result > userFlowRiskControlConfiguration.getMaxAccessCount()) {
            handleException(servletResponse, JSON.toJSONString(Results.failure(new ClientException("当前系统繁忙，请稍后再试"))));
            return;
        }

        filterChain.doFilter(servletRequest, servletResponse);


    }

    /**
     * 处里过滤器中抛出的异常
     */
    private void handleException(ServletResponse response, String json) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        response.setCharacterEncoding("UTF-8");
        httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);

        try(PrintWriter writer = httpResponse.getWriter()) {
            writer.write(json);
        } catch (Exception e) {

        }
    }
}
